﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace meituan
{
    public partial class FormPinglun : Form
    {
        Thread thread;

        public FormPinglun()
        {
            InitializeComponent();
        }

        private void buttonSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.*)|*.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string[] files = dialog.FileNames;
                foreach (string file in files)
                {
                    listBoxDianpu.Items.Add(file);
                }
            }
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            listViewDianpu.Columns.Add("");
            listViewDianpu.Columns[0].Width = 40;
            listViewDianpu.Columns.Add("ID");
            listViewDianpu.Columns[1].Width = 70;
            listViewDianpu.Columns.Add("标题");
            listViewDianpu.Columns[2].Width = 120;
            listViewDianpu.Columns.Add("文件名");
            listViewDianpu.Columns[3].Width = 120;

            listViewDianpu2.Columns.Add("");
            listViewDianpu2.Columns[0].Width = 40;
            listViewDianpu2.Columns.Add("ID");
            listViewDianpu2.Columns[1].Width = 70;
            listViewDianpu2.Columns.Add("标题");
            listViewDianpu2.Columns[2].Width = 120;
            listViewDianpu2.Columns.Add("文件名");
            listViewDianpu2.Columns[3].Width = 120;
            int index = 0;
            foreach (string boxitem in listBoxDianpu.Items)
            {
                string fileName = System.IO.Path.GetFileNameWithoutExtension(boxitem);
                DataTable dt = Excel.ReadDataFromCsv(boxitem);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListViewItem item = new ListViewItem();
                    item.SubItems[0].Text = index.ToString();
                    item.SubItems.Add(dt.Rows[i][0].ToString());
                    item.SubItems.Add(dt.Rows[i][1].ToString());
                    item.SubItems.Add(fileName);
                    listViewDianpu.Items.Add(item);
                    index++;
                }
            }
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            int selectCount = listViewDianpu.SelectedItems.Count;
            Console.WriteLine(selectCount);
            if (selectCount > 0)
            {
                for (int i = 0; i < selectCount; i++)
                {
                    int index = Convert.ToInt32(listViewDianpu.SelectedItems[i].Text);
                    listViewDianpu2.Items.Add((ListViewItem)listViewDianpu.Items[index].Clone());
                }
            }
        }

        private void buttonRemove_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewDianpu2.SelectedItems)
            {
                if (item.Selected)
                {
                    item.Remove();
                }
            }
        }

        private void buttonSelectAll_Click(object sender, EventArgs e)
        {
            listViewDianpu2.Items.Clear();
            for (int i = 0; i < listViewDianpu.Items.Count; i++)
            {
                int index = Convert.ToInt32(listViewDianpu.Items[i].Text);
                listViewDianpu2.Items.Add((ListViewItem)listViewDianpu.Items[index].Clone());
            }
        }

        private void buttonClear_Click(object sender, EventArgs e)
        {
            listViewDianpu2.Items.Clear();
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            if (buttonStart.Text == "开始")
            {
                Dictionary<string, string> config = Utils.getConfig();
                if (config == null)
                {
                    MessageBox.Show("请设置配置");
                    return;
                }

                if (listViewDianpu2.Items.Count == 0)
                {
                    MessageBox.Show("请先添加");
                    return;
                }

                foreach (Control ctl in this.Controls)
                {
                    if (ctl is Button)
                    {
                        Button btn = ctl as Button;
                        btn.Enabled = false;
                    }
                }
                buttonStart.Text = "停止";
                buttonStart.Enabled = true;

                if (thread == null)
                {
                    run(config);
                }
                else
                {
                    MessageBox.Show("线程正在执行");
                }
            }
            else
            {
                thread.Abort();
                while (true)
                {
                    Thread.Sleep(1000);
                    Console.WriteLine(thread.IsAlive);
                    if (!thread.IsAlive)
                    {
                        thread = null;
                        foreach (Control ctl in this.Controls)
                        {
                            if (ctl is Button)
                            {
                                Button btn = ctl as Button;
                                btn.Enabled = true;
                            }
                        }
                        buttonStart.Text = "开始";
                        break;
                    }
                }
            }
        }

        private void run(Dictionary<string, string> config)
        {
            ArrayList arr = new ArrayList();
            foreach (ListViewItem item in listViewDianpu2.Items)
            {
                string id = item.SubItems[1].Text;
                string dianpu = item.SubItems[2].Text;
                string fileName = item.SubItems[3].Text;

                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("id", id);
                dic.Add("dianpu", dianpu);
                dic.Add("fileName", fileName + "_评论");

                arr.Add(dic);
            }
            thread = new Thread(new ThreadStart(() => {
                int pageSize = 50;
                int offset = 0;
                foreach (Dictionary<string, string> i in arr)
                {
                    string id = i["id"];
                    string dianpu = i["dianpu"];
                    string fileName = i["fileName"];

                    string originUrl = $"https%3A%2F%2Fwww.meituan.com%2Fmeishi%2F{id}%2F";
                    string uuid = Utils.GetUuid();
                    string url = $"https://www.meituan.com/meishi/api/poi/getMerchantComment?uuid={uuid}&platform=1&partner=126&originUrl={originUrl}&riskLevel=1&optimusCode=10&id={id}&offset={offset}&pageSize={pageSize}&sortType=1";
                    Console.WriteLine(url);
                    Invoke(new Action<string>((x) => {
                        textBoxInfo.Text += x.ToString();
                        textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                        textBoxInfo.ScrollToCaret();
                    }), url);

                    bool flag = false;
                    if (config["isProxy"] == "1")
                    {
                        flag = true;
                    }
                    string res = Utils.HttpGet(url, "", flag);
                    if (res == null)
                    {
                        Invoke(new Action<string>((x) => {
                            textBoxInfo.Text += x.ToString();
                            textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                            textBoxInfo.ScrollToCaret();
                        }), "请求失败！\n");
                        continue;
                    }
                    JObject jo = (JObject)JsonConvert.DeserializeObject(res);
                    string strData = "";
                    foreach (JObject data in jo["data"]["comments"])
                    {
                        string picUrls = "";
                        foreach (JObject picUrl in data["picUrls"])
                        {
                            picUrls += picUrl["url"] + "|";
                        }
                        picUrls = picUrls.TrimEnd('|');

                        strData +=
                        id + "," +
                        Convert.ToString(data["userName"]).Replace(',', '，').Replace("\r", "").Replace("\n", "") + "," +
                        data["userUrl"] + "," +
                        Convert.ToString(data["comment"]).Replace(',', '，').Replace("\r", "").Replace("\n", "") + "," +
                        Convert.ToString(data["merchantComment"]).Replace(',', '，').Replace("\r", "").Replace("\n", "") + "," +
                        picUrls + "," +
                        Convert.ToString(data["menu"]).Replace(',', '，').Replace("\r", "").Replace("\n", "") + "," +
                        data["commentTime"] + "\n";
                    }
                    Excel.WriteToCSV(config["dataPath"] + "\\评论", fileName, strData, true);
                    Invoke(new Action<string>((x) =>
                    {
                        textBoxInfo.Text += x.ToString();
                        textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                        textBoxInfo.ScrollToCaret();
                    }), String.Format("{0}_{1} 完毕\n", id, dianpu));

                    Random rd = new Random();
                    int num = rd.Next(int.Parse(config["timeMin"]), int.Parse(config["timeMax"]));

                    Invoke(new Action<string>((x) => {
                        textBoxInfo.Text += x.ToString();
                        textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                        textBoxInfo.ScrollToCaret();
                    }), strData + "\n等待" + num + "后执行下一次请求\n");
                    Thread.Sleep(num * 1000);
                }
                Invoke(new Action<string>((x) => {
                    textBoxInfo.Text += x.ToString();
                    textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                    textBoxInfo.ScrollToCaret();
                    foreach (Control ctl in this.Controls)
                    {
                        if (ctl is Button)
                        {
                            Button btn = ctl as Button;
                            btn.Enabled = true;
                        }
                    }
                    buttonStart.Text = "开始";
                }), "全部完毕");
                MessageBox.Show("全部完毕");
            }));
            thread.IsBackground = true;
            thread.Start();
        }

        
    }
}
